<?php
namespace Home\Controller;
use Home\Controller\BaseController;
require_once 'Qiniu/autoload.php';
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
C('TOKEN_ON', false);

class LiveController extends BaseController {


public function index() {
        $model=M('Live');
        $map = array();
        $title = I('get.title');
        $s_time = I('get.s_time', 0);
        $e_time = I('get.e_time', 0);

        $map = 'v_status <> -1';
        if($title) {
//            $map['title'] = array('like', "%{$title}%");
            $map .= ' AND title like "%' . $title . '%"';
        }

        if($s_time || $e_time) {
            $e_time = $e_time ? strtotime($e_time . '23:59:59') : (time() + (20 * 365 * 24 * 60 * 60));
//            $map['start_time'] = array(array('egt', strtotime($s_time)), array('elt', $e_time));
            $map .= ' AND start_time >= ' . strtotime($s_time) . ' AND start_time <= ' . $e_time;
        }

        if(session('is_admin')) {
            $map .= ' AND column_id in (' . implode(',', $this->channelId) . ')';
        } else {
            if(session('is_type') == 0) {
                $map .= ' AND user_id = ' . session('organ_id');
            } elseif(session('is_type') == 1) {
                $map .= ' AND (column_id in (' . implode(',', $this->channelId) . ') OR user_id = ' . session('organ_id') . ')';
            }
        }

        $total = $model->alias('live')->where($map)->group('group_id')->join('__USER_INFO__ u ON u.uid=live.apply_id','left')->select();
        $total=count($total);
        $page = new \Think\Page($total, 8);
        $page->rollPage = 7;
        $show = $page->show();

        $liveList = $model
            ->where($map)
            ->alias('live')
            ->group('group_id')
            ->join('__USER_INFO__ u ON u.uid=live.apply_id','left')
            ->order('start_time DESC')
            ->limit($page->firstRow .',' . $page->listRows)
            ->select();
//        echo $model->getLastsql();

        $columeList=M('front_category')->where(array('status'=>1))->select();

        $this->assign('channelIds', $this->channelId);
        $this->assign('showpage', $show);
        $this->assign('liveList', $liveList);
        $this->assign('columeList', $columeList);
        $this->assign('active', '直播管理');
        $this->display();
    }


    /**
     * 直播详情
     */
    public function liveinfo() {
        $group_id = I('get.group_id');
        if($group_id){

            $is_ext = M('Live')->where(array('group_id' => $group_id))->find();
            if(!$is_ext)
                $this->error('对不起，此直播不存在！',U('live_list'));

            $is_admin = session('is_admin');
            $is_type = session('is_type');

            $where = 'group_id = "' . $group_id . '"';
            if($is_admin) {
                if(!in_array($is_ext['column_id'], $this->channelId)) {
                    $this->error('对不起，您没有权限管理此直播');
                }

//                $where = ' AND column_id in (' . implode(',', $this->channelId) . ')';
            } else {
                $owner = M('Live')->where(array('group_id' => $group_id,'user_id' => session('organ_id')))->find();
                if($is_type) {
                    if(!in_array($is_ext['column_id'], $this->channelId)) {
                        if(!$owner) {
                            $this->error('对不起，您没有权限管理此直播');
                        }
                    }
                } else {
                    if(!$owner) {
                        $this->error('对不起，您没有权限管理此直播');
                    }
                }

//                $where .= ' AND user_id = ' . session('organ_id');
            }

            $model=M('Live');
            $streamList = $model
                ->alias('live')
                ->where($where)
                ->join('__USER_INFO__ u ON u.uid=live.user_id','inner')
                ->order('pos_sort asc, id DESC')
                ->select();
//            echo '<pre>';
//            print_r($model->getLastsql());exit;
            $subQuery = 'SELECT COUNT(t.id) total FROM (SELECT id FROM `whtvjw_pv` WHERE `group_id` = "' . $group_id . '" GROUP BY ip) t';
            $seeTotal = M()->query($subQuery);

            //七牛对象存储的上传凭证
            $putPolicy=array(
                'saveKey'=>'liveList/$(etag)',
            );
            $upAuth = new Auth(C('QINIU_AK'), C('QINIU_SK'));
            $bucket = C('QINIU_BUCKET');
            $uploadToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);
            $putPolicy['returnUrl']='http://'.I('server.HTTP_HOST').U('uploadLiveThumb');
            $putPolicy['returnBody']=json_encode(array(
                "filename"=>"$(key)",
                "liveId"=>"$(x:liveId)"
            ));
            $liveToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);

            $this->assign('uploadToken', $uploadToken);
            $this->assign('liveToken', $liveToken);
            $this->assign('streamList', $streamList);
            $this->assign('seeTotal', $seeTotal[0]['total']);
            $this->display();
        } else {
            $this->error('参数错误' );
        }
    }

    public function updateDetail() {
        $live_intro = I('post.live_intro', '');
        $group_id = I('post.group_id', '');
        $title = I('post.title', '');
        $return_live = I('post.return_live', '');
        $start_time = I('post.start_time', 0);
        $filename = I("post.image_url");

        if($group_id) {
            if($title) {
                $title && $dataGet['title'] = $title;
                $live_intro && $dataGet['intro'] = $live_intro;
                $return_live && $dataGet['return_live'] = $return_live;
                $start_time && $dataGet['start_time'] = strtotime($start_time);
                if($filename){
                    $filename &&  $dataGet['image_url'] = $filename;
                }


                $res = M('Live')->where(array('group_id' => $group_id))->save($dataGet);

                if($res !== false) {
                    $this->success('设置成功');
                } else {
                    $this->error('设置失败，请重新操作');
                }

            } else {
                $this->error('直播标题不能为空');
            }
        } else {
            $this->error('直播不存在');
        }
    }


    /**
     * 上传每个机位的缩略图
     * @return [type] [description]
     */
    public function uploadLiveThumb() {
        $upload_ret=I('get.upload_ret');
        $upload_ret=json_decode(\Qiniu\base64_urlSafeDecode($upload_ret),true);

        $filename =is_array($upload_ret)?$upload_ret['filename']:"";
        $live_id = is_array($upload_ret)?$upload_ret['liveId']:"";
        if($live_id) {
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');

            if($filename) {
                $dataGet['thumb'] = C('IMAGE_HOST').$filename;
                $dataGet['id'] = $live_id;

                $res = M('Live')->save($dataGet);

                if($res !== false) {
                    $this->success('设置成功');
                } else {
                    $this->error('设置失败，请重新操作');
                }


            } else {
                $this->error('上传失败');
            }

        } else {
            $this->error('直播不存在');
        }
    }
    


    public function ajax_get_vstatus(){
        $id=I('get.id');
        if($id){
            echo M('Live')->getFieldById('v_status',$id);
        }else{
            echo -1;
        }
    }

    public function ajaxStreamOn(){
        // $live_id=I('get.liveId');
        // $stream=I('get.stream');
        // if($live_id&&$stream){
        //     $this->ajaxReturn(liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),1));
        // }

        $live_id=I('get.liveId');
        $stream=I('get.stream');
        $message['groupId']=-1;
        if($live_id&&$stream){
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');
            // $count1 = M('Live')->where(array('group_id' => $group_id))->count();
            //$this->checkAuth($group_id);

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),1);
            if($res['status'] == 0) {
                M('Live')->where(array('id' => $live_id))->save(array(
                    'update_time' => time(),
                ));

                $group_status = M('Live')->where(array('id' => $live_id))->getField('group_status');

                if($group_status != 1) {
                    $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                        'group_status' => 1,
                    ));
                    $message['groupId'] = 1;
                }

                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/
                // $count2 = M('Live')->where(array('group_id' => $group_id, 'z_status' => 1))->count();
                // if($count1 == $count2) {
                //     $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                //         'group_status' => 1,
                //     ));
                //     $message['groupId'] = 1;
                // }

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];

                foreach ($uidList as $key => $value) {
                    if($value == $liveinfo['user_id'])
                        unset($uidList[$key]);
                }

                // $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');

                // 推送直播人
                $trans=json_encode(array('pushCode'=>301,'objectId'=>$live_id,'userId'=>0,'liveTitle' => $liveinfo['title']));
                sock_post(C('MAIN_HOST'). 'Tui/pushUid.html', array('uid'=>$liveinfo['user_id'],'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));


                if($message['groupId'] == 1) {
                    $trans=json_encode(array('pushCode'=>300,'objectId'=>$live_id,'userId'=>0));
                    sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));
                }
                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);


            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }

    }


    public function ajaxGroupStreamOn($group_id){
        if($group_id){
            //$this->checkAuth($group_id);

            $ids = M('Live')->where(array('group_id' => $group_id))->select();
            $tmp = array();
            foreach($ids as $k => $val) {
                $tmp[$k]['id'] = $val['id'];
                $tmp[$k]['stream'] = $val['group_id'] . '_' . $val['user_id'];
            }

            $res = liveStatus(2, $tmp,1);
            if($res['status'] == 0) {
                $r = M('Live')->where(array('group_id' => $group_id,'z_status'=>array('neq',3)))->save(array(
                    'group_status' => 1,
                    'z_status' => 1,
                ));

                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/

                $map['id'] = $ids[0]['id'];
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];

                $users = array();
                foreach($ids as $val) {
                    $users[] = $val['user_id'];
                }

                foreach ($uidList as $key => $value) {
                    foreach ($users as $k => $v) {
                        if($v == $value)
                            unset($uidList[$key]);
                    }
                }

                // $uidList = array_merge($uidList, $users);
                $uidList = array_unique($uidList);

                $applyname = M('UserInfo')->where(array('uid' => $ids[0]['apply_id']))->getField('realname');

                // 管理员推送
                $trans=json_encode(array('pushCode'=>300,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));

                foreach ($ids as $key => $value) {
                    // 直播人推送
                    $trans=json_encode(array('pushCode'=>301,'objectId'=>$value['id'],'userId'=>0,'liveTitle' => $liveinfo['title']));
                    sock_post(C('MAIN_HOST'). 'Tui/pushUid.html', array('uid'=>$value['user_id'],'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已开启','trans'=>$trans));

                }


                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }
    }


    public function ajaxGroupStreamOff($group_id){
        if($group_id){
            //$this->checkAuth($group_id);

            $ids = M('Live')->where(array('group_id' => $group_id))->select();
            $tmp = array();
            foreach($ids as $k => $val) {
                $tmp[$k]['id'] = $val['id'];
                $tmp[$k]['stream'] = $val['group_id'] . '_' . $val['user_id'];
            }

            $res = liveStatus(2, $tmp,0);
            if($res['status'] == 0) {
                $r = M('Live')->where(array('group_id' => $group_id,'z_status'=>array('neq',3)))->save(array(
                    'group_status' => 0,
                    'z_status' => 0,
                ));

                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/

                // 推送
                $map['id'] = $ids[0]['id'];
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $users = array();
                foreach($ids as $val) {
                    $users[] = $val['user_id'];
                }

                foreach ($uidList as $key => $value) {
                    foreach ($users as $k => $v) {
                        if($v == $value)
                            unset($uidList[$key]);
                    }
                }

                // $uidList = array_merge($uidList, $users);
                $uidList = array_unique($uidList);

                $applyname = M('UserInfo')->where(array('uid' => $ids[0]['apply_id']))->getField('realname');

                // \Think\Log::write(implode(',', $uidList),'uidList');
                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已终止','trans'=>$trans));

                // 直播人推送
                // $trans=json_encode(array('pushCode'=>301,'objectId'=>$ids[0]['id'],'userId'=>0,'liveTitle' => $liveinfo['title']));
                // sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$users,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播已终止','trans'=>$trans));

                foreach ($ids as $key => $value) {
                    // 直播人推送
                    $trans=json_encode(array('pushCode'=>302,'objectId'=>$value['id'],'userId'=>0,'liveTitle' => $liveinfo['title']));
                    sock_post(C('MAIN_HOST'). 'Tui/pushUid.html', array('uid'=>$value['user_id'],'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播通道已终止','trans'=>$trans));

                }
                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }
    }

    public function ajaxLiveStatusOff($group_id){
        if($group_id){
            //$this->checkAuth($group_id);

            $ids = M('Live')->where(array('group_id' => $group_id))->select();

            $tmp = array();
            foreach($ids as $k => $val) {
                $tmp[$k]['id'] = $val['id'];
                $tmp[$k]['stream'] = $val['group_id'] . '_' . $val['user_id'];
            }

            $res = liveStatus(2, $tmp,3);
            if($res['status'] == 0) {
                $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                    'group_status' => 3,
                    'z_status' => 3,
                ));

                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/
                /*$action = A('Oss');
                foreach($ids as $k => $val) {
                     // 拉取回看m3u8地址

                    $mlist = $action->ajaxM3u8List($val['id']);
                    M('Live')->where(array('id' => $val['id']))->save(array(
                        'return_live' => $mlist[count($mlist) - 1]['RecordUrl'],
                    ));
                }*/

                // 推送
                $map['id'] = $ids[0]['id'];
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $liveUserList = M('Live')->where(array('group_id' => $group_id))->select();
                $users = array();
                foreach($liveUserList as $val) {
                    $users[] = $val['user_id'];
                }

                foreach ($uidList as $key => $value) {
                    foreach ($users as $k => $v) {
                        if($v == $value)
                            unset($uidList[$key]);
                    }
                }

                // $uidList = array_merge($uidList, $users);
                $uidList = array_unique($uidList);

                $applyname = M('UserInfo')->where(array('uid' => $ids[0]['apply_id']))->getField('realname');

                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $ids[0]['title'] . '》直播已结束','trans'=>$trans));
                // 直播人推送
                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$users,'title'=>'见微','content'=>'申请人：' . $applyname . '的《' . $ids[0]['title'] . '》直播已结束','trans'=>$trans));


                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }

        }
    }

    public function ajaxLiveStatusOn(){
        $group_id=I('get.groupid');
        if($group_id){
            //$this->checkAuth($group_id);

            $ids = M('Live')->where(array('group_id' => $group_id))->select();

            $tmp = array();
            foreach($ids as $k => $val) {
                $tmp[$k]['id'] = $val['id'];
                $tmp[$k]['stream'] = $val['group_id'] . '_' . $val['user_id'];
            }

            $res = liveStatus(2, $tmp,0);
            if($res['status'] == 0) {
                $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                    'group_status' => 0,
                    'z_status' => 0,
                ));

                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/
                $action = A('Oss');
                foreach($ids as $k => $val) {
                    // 拉取回看m3u8地址

                    $mlist = $action->ajaxM3u8List($val['id']);
                    M('Live')->where(array('id' => $val['id']))->save(array(
                        'return_live' => $mlist[count($mlist) - 1]['RecordUrl'],
                    ));
                }

                // 推送
                $map['id'] = $ids[0]['id'];
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $liveUserList = M('Live')->where(array('group_id' => $group_id))->select();
                $users = array();
                foreach($liveUserList as $val) {
                    $users[] = $val['user_id'];
                }

                foreach ($uidList as $key => $value) {
                    foreach ($users as $k => $v) {
                        if($v == $value)
                            unset($uidList[$key]);
                    }
                }

                // $uidList = array_merge($uidList, $users);
                $uidList = array_unique($uidList);

                $applyname = M('UserInfo')->where(array('uid' => $ids[0]['apply_id']))->getField('realname');

                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'《' . $ids[0]['title'] . '》直播已开始','trans'=>$trans));
                // 直播人推送
                $trans=json_encode(array('pushCode'=>302,'objectId'=>$ids[0]['id'],'userId'=>0));
                sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$users,'title'=>'见微','content'=>'申请人：' . $applyname . '的《' . $ids[0]['title'] . '》直播已开始','trans'=>$trans));


                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }

        }
    }


    public function ajaxLiveOn(){
        // $live_id=I('get.liveId');
        // $stream=I('get.stream');
        // if($live_id&&$stream){
        //     $this->ajaxReturn(liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),2));
        // }

        $live_id=I('get.liveId');
        $stream=I('get.stream');
        $message['groupId']=-1;
        if($live_id&&$stream){
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');
            $count1 = M('Live')->where(array('group_id' => $group_id))->count();

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),2);
            if($res['status'] == 0) {
                $count2 = M('Live')->where(array('group_id' => $group_id, 'z_status' => 2))->count();
                if($count1 == $count2) {
                    $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                        'group_status' => 2,
                    ));
                    $message['groupId']=2;
                }

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');

                sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播已开始','trans'=>$trans));

                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }

    }

    public function ajaxLiveOff(){
        // $live_id=I('get.liveId');
        // $stream=I('get.stream');
        // if($live_id&&$stream){
        //     $this->ajaxReturn(liveStatus(1, array(array('id'=>$live_id,'stream'=>$stream)),3));
        // }
        //

        $live_id=I('get.liveId');
        $stream=I('get.stream');
        $message['groupId']=-1;
        if($live_id&&$stream){
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');
            $count1 = M('Live')->where(array('group_id' => $group_id))->count();

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),3);
            if($res['status'] == 0) {
                $count2 = M('Live')->where(array('group_id' => $group_id, 'z_status' => 3))->count();
                if($count1 == $count2) {
                    $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                        'group_status' => 3,
                    ));
                    $message['groupId']=3;
                }

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');

                sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播已结束','trans'=>$trans));

                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }

    }

    public function ajaxStreamOff(){
        $live_id=I('get.liveId');
        $stream=I('get.stream');
        $message['groupId']=-1;
        if($live_id&&$stream){
            $group_id = M('Live')->where(array('id' => $live_id))->getField('group_id');

            //$this->checkAuth($group_id);

            $count1 = M('Live')->where(array('group_id' => $group_id))->count();

            $res = liveStatus(2, array(array('id'=>$live_id,'stream'=>$stream)),0);
            if($res['status'] == 0) {
                $count2 = M('Live')->where(array('group_id' => $group_id, 'z_status' => 0))->count();
                if($count1 == $count2) {
                    $r = M('Live')->where(array('group_id' => $group_id))->save(array(
                        'group_status' => 0,
                    ));
                    $message['groupId'] = 0;
                }

                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/

                // 推送
                $map['id'] = $live_id;
                $liveinfo = M('Live')
                    ->alias('l')
                    ->join('__CHANNEL__ ch ON l.column_id=ch.chid','left')
                    ->field("l.id,l.user_id,l.title,l.v_status,l.z_status,l.group_id,l.apply_id,l.intro,ch.relation,l.back_reason,l.v_user_id,l.start_time,l.address,l.group_status")
                    ->where($map)->find();
                $uidList = array();
                $approve = unserialize($liveinfo['relation']);
                $uidList = $approve[0];
                foreach ($uidList as $key => $value) {
                    if($value == $liveinfo['user_id'])
                        unset($uidList[$key]);
                }

                // $uidList[] = $liveinfo['user_id'];
                $uidList = array_unique($uidList);
                $livename = M('UserInfo')->where(array('uid' => $liveinfo['user_id']))->getField('realname');

                // 推送管理员
                // $trans=json_encode(array('pushCode'=>300,'objectId'=>$live_id,'userId'=>0));
                // sock_post('C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播已被中断','trans'=>$trans));

                // 推送直播人
                $trans=json_encode(array('pushCode'=>302,'objectId'=>$live_id,'userId'=>0));
                sock_post(C('MAIN_HOST'). 'Tui/pushUid.html', array('uid'=>$liveinfo['user_id'],'title'=>'见微','content'=>'直播人：' . $livename . '的《' . $liveinfo['title'] . '》直播已被中断','trans'=>$trans));

                if($message['groupId'] == 0) {
                    // 推送管理员
                    $trans=json_encode(array('pushCode'=>302,'objectId'=>$live_id,'userId'=>0));
                    sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=> '《' . $liveinfo['title'] . '》直播已被中断','trans'=>$trans));

                    // $liveUserList = M('Live')->where(array('group_id' => $liveinfo['group_id']))->select();
                    // $users = array();
                    // foreach($liveUserList as $val) {
                    //     if($liveinfo['user_id'] != $val) {
                    //          $users[] = $val['user_id'];
                    //     }
                    // }

                    // // 推送直播人
                    // $trans=json_encode(array('pushCode'=>302,'objectId'=>$live_id,'userId'=>0));
                    // sock_post(C('MAIN_HOST'). 'Tui/pushUidList.html', array('uids'=>$users,'title'=>'见微','content'=>'《' . $liveinfo['title'] . '》直播已被中断','trans'=>$trans));

                }

                $message['status'] = 0;
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);

            } else {
                $message['status'] = 1;
                $message['msg'] = '服务器异常';
                $this->ajaxReturn($message);
            }
        }
    }

    public function showBTNs($id){
        if($id){
            $str='';
            $zStatus=M('Live')->getFieldById($id,'z_status');
            $info = M('Live')->where(array('id' => $id))->find();

            $uid = session('liveadmin_uid');
            $is_admin = session('is_admin');
            $auth = M('LiveAuth')->where(array('group_id' => $info['group_id'], 'user_id' => $uid))->find();

            switch($zStatus){
                case 0:
                    $str .= '<li class="pull-left item-btn active" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</li>';
                    $str .= '<li class="btn pull-left item-btn" data-status="1"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</li>';
                    $str .= '<li class="btn pull-left item-btn" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</li>';
//                    $str.='<botton type="button" class="btn btn-xs btn-success" disabled data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</botton>';
//                    $str.='<botton type="button" class="btn btn-xs btn-default" data-status="1"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</botton>';
//                    $str.='<botton type="button" class="btn btn-xs btn-default" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</botton>';

                        /*$str.='<botton type="button" class="btn btn-xs btn-default testing" data-status="4"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">测试</botton>';*/
//                    $str.='</div>';
//                    $str .= ' <span><img src="/Public/images/status-yellow.png" alt="" align="center"> 已审核</span>';
                    break;
                case 2:
                    $str .= '<li class="btn pull-left item-btn" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</li>';
                    $str .= '<li class="pull-left item-btn active" data-status="1"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</li>';
                    $str .= '<li class="btn pull-left item-btn" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</li>';
//                    $str.='<botton type="button" class="btn btn-xs btn-default" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</botton>';
//                    $str.='<botton type="button" class="btn btn-xs btn-success" data-status="1" disabled   data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</botton>';
//                    $str.='<botton type="button" class="btn btn-xs btn-default" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</botton>';

                        /*$str.='<botton type="button" class="btn btn-xs btn-default testing" data-status="4"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">测试</botton>';*/

//                    $str.='</div>';
//                    $str .= ' <span><img src="/Public/images/status-red.png" alt="" align="center"> 直播中</span>';
                    break;
                case 1:

                    $str .= '<li class="btn pull-left item-btn" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</li>';
                    $str .= '<li class="pull-left item-btn active" data-status="1"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</li>';
                    $str .= '<li class="btn pull-left item-btn" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</li>';
//                    $str.='<botton type="button" class="btn btn-xs btn-default" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</botton>';
//                    $str.='<botton type="button" class="btn btn-xs btn-success" data-status="1" disabled   data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</botton>';
//                    $str.='<botton type="button" class="btn btn-xs btn-default" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</botton>';

                        /*$str.='<botton type="button" class="btn btn-xs btn-default testing" data-status="4"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">测试</botton>';*/
//                    $str.='</div>';
//                    $str .= ' <span><img src="/Public/images/status-green.png" alt="" align="center"> 待直播</span>';
                    break;


                case 3:

                    $str .= '<li class="btn pull-left item-btn" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</li>';
                    $str .= '<li class="btn btn pull-left item-btn" data-status="1"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</li>';
                    $str .= '<li class="pull-left item-btn active" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</li>';

//                    $str.='</div>';
//                    $str = ' <img src="/Public/images/status-gray.png" alt="" align="center"> 直播结束';
                    break;

                /*case 4:
                    if($auth['is_manage'] == 1 || $is_admin == 1) {
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="0"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">预告</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="1"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">直播</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-success" data-status="4" disabled   data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">测试</botton>';
                        $str.='<botton type="button" class="btn btn-xs btn-default" data-status="3"  data-id="' . $id . '" data-stream="' . $info['group_id'] . '_' . $info['user_id'].'">回看</botton>';
                    }
                    $str.='</div>';
                    $str = ' <img src="/Public/images/status-gray.png" alt="" align="center"> 测试中';

                    break;*/
            }

            echo $str;
        }
    }

    /*public function ajaxDelLive(){
        if(IS_GET) {
            $id = I('get.id');
        } elseif(IS_POST) {
            $id = I('post.id');
            is_array($id) && $id = implode(',', $id);
        }

        if(empty($id)) {
            $message['status'] = -1;
            $message['msg'] = '选项不能为空';
            $this->ajaxReturn($message);
        }

        $map['group_id'] = array('in', $id);

        $res = M('Live')->where($map)->delete();
        if($res) {
            $message['status'] = 1;
            $message['msg'] = '删除成功';
            $this->ajaxReturn($message);
        } else {
            $message['status'] = -1;
            $message['msg'] = '删除失败，请重试';
            $this->ajaxReturn($message);
        }
    }*/

    public function _empty(){
        echo "";
    }

    public function ajaxEditPosName($id="",$posName=""){
        if($id && $posName){
            $group_id = M('Live')->where(array('id' => $id))->getField('group_id');
            //$this->checkAuth($group_id);

            $data['id']=$id;
            $data['pos_name']=$posName;
            $res=M("Live")->save($data);
            if($res){
                $group_id=M('Live')->getFieldById($id,"group_id");
                /*$mkHTML=new \Common\Util\makeHTML();
                $mkHTML-> ByGroupId($group_id);*/
            }
            $this->ajaxReturn($res);
        }else{
            $this->ajaxReturn(0);
        }
    }

    public function ajaxGetDetail() {
        $group_id = I('get.group_id', '');
        if($group_id) {
            $info = M('Live')->field('title, live_intro, image_url')->where(array('group_id' => $group_id))->find();
            if($info) {
                $this->ajaxReturn($info);
            } else {
                $this->ajaxReturn(0);
            }

        } else {
            $this->ajaxReturn(0);
        }
    }

    /**
     * 直播流在线人数
     * @return [type] [description]
     */
    public function getOnlineNumber($sTime,$eTime) {
        $live_id = I('get.id');
        if($live_id) {
            $info = M('Live')->where(array('id' => $live_id))->find();
            if($info) {

                $info['Action'] = 'DescribeLiveStreamOnlineUserNum';
                $info['DomainName'] = 'jwlive.appwuhan.com';
                $info['AppName'] = 'jw';
                $info['StreamName'] = $info['group_id'] . '_' . $info['user_id'];

                $requestid = callAliyunApi($info);
                $requestid = json_decode($requestid, true);
                if(isset($requestid['TotalUserNumber']) && isset($requestid['OnlineUserInfo'])) {
                    $message['status'] = 1;
                    $message['info'] = $requestid;
                    $this->ajaxReturn($message);
                }

            } else {

                $message['status'] = -1;
                $message['msg'] = '直播不存在';
            }

        } else {
            $message['status'] = -1;
            $message['msg'] = '未知ID';
        }

        $this->ajaxReturn($message);
    }


    /**
     * 根据ID获取指定的推流是否在线
     * @return [type] [description]
     */
    public function getStreamById() {
        $live_id = I('get.id');
        if($live_id) {
            $info = M('Live')->where(array('id' => $live_id))->find();
            if($info) {

                $info['Action'] = 'DescribeLiveStreamsOnlineList';
                $info['DomainName'] = 'jwlive.appwuhan.com';
                $info['AppName'] = 'jw';

                $requestid = callAliyunApi($info);
                $requestid = json_decode($requestid, true);
                dump($requestid);
                // print_r($requestid);exit;
                if(isset($requestid['OnlineInfo']['LiveStreamOnlineInfo'])) {
                    if(!empty($requestid['OnlineInfo']['LiveStreamOnlineInfo'])) {
                        foreach($requestid['OnlineInfo']['LiveStreamOnlineInfo'] as $val) {
                            $streamName = $info['group_id'] . '_' . $info['user_id'];
                            if($val['StreamName'] == $streamName) {
                                $message['status'] = 1;
                                $message['is_push'] = 1; // 表示正在推流
                                $this->ajaxReturn($message);
                            }
                        }

                    } else {

                        $message['status'] = 1;
                        $message['is_push'] = 0; // 表示未推流
                        $this->ajaxReturn($message);
                    }

                }

            } else {

                $message['status'] = -1;
                $message['msg'] = '直播不存在';
            }

        } else {
            $message['status'] = -1;
            $message['msg'] = '未知ID';
        }

        $this->ajaxReturn($message);
    }

    public function ajaxGetSort() {
        $group_id = I('get.group_id');
        if($group_id) {
            $list = M('Live')->field('id, pos_sort')->where(array('group_id' => $group_id))->select();
            if($list) {
                $this->ajaxReturn($list);
            } else {
                $this->ajaxReturn(0);
            }

        } else {
            $this->ajaxReturn(0);
        }
    }

    public function ajaxUpdateSort() {
        $arr = I('post.data');
        $group_id = I('get.group_id');

        //$this->checkAuth($group_id);

        if($arr) {
            foreach($arr as $val) {
                $res = M('Live')->where(array('id' => $val[0]))->save(array(
                    'pos_sort' => intval($val[1]),
                ));
            }
            /*$mkHTML=new \Common\Util\makeHTML();
            $mkHTML-> ByGroupId($group_id);*/

            $this->ajaxReturn(1);
        } else {
            $this->ajaxReturn(0);
        }
    }
    /*
        public function ajaxReporterList() {
            $q = I('get.q');
            $group_id = I('get.group_id');

            $output = '';
            $auth = M('LiveAuth')->where(array('group_id' => $group_id))->getField('user_ids');
            $auth = unserialize($auth);
            $con['uid'] = array('in', $auth);
            $authList = M('UserInfo')->where($con)->select();

            foreach($authList as $val) {
                $output .= '<li><input type="checkbox" name="id[]" value="' . $val['uid'] . '"</li><label>' . $val['realname'] . '</label>';
            }

            if($q) {
                $map['realname'] = $q;
                $map['mobile'] = $q;
                $map['realnamepy'] = $q;
                $map['_logic'] = 'OR';

                $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')
                        ->where($map)->select();
                $output .= '<hr />';
                foreach($list as $val) {
                    $output .= '<li><input type="checkbox" name="id[]" value="' . $val['uid'] . '"</li><label>' . $val['realname'] . '</label>';
                }
            }

            echo $output;
        }*/

    /**
     * 获取全部用户列表
     * @return [type] [description]
     */
    public function getReporterList() {
        $uid = session('liveadmin_uid');
        $channel = M('Admin')->where(array('id' => $uid))->getField('liveauth');

        $users = array();
        if($channel) {
            $map['userchannel'] = array('in', $channel);
            if($channel==='*'){
                $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')->select();
            }else{
                $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')->where($map)->select();
            }
            foreach ($list as $key => $value) {
                $users[$key]['uid'] = $value['uid'];
                $users[$key]['realname'] = $value['realname'];
            }
        }


        return $users;
    }

    /**
     * 获取有权限的用户列表
     * @return [type] [description]
     */
    public function getReporterListByGroup($group_id) {

        $user_list = M('LiveAuth')->where(array('group_id' => $group_id))->select();
        $user_ids = array();

        foreach($user_list as $val) {
            $user_ids[] = $val['user_id'];
        }

        $users = array();
        if($user_ids) {
            $map['u.uid'] = array('in', $user_ids);
            $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')->where($map)->select();
            $users = array();
            foreach ($list as $key => $value) {
                $users[$key]['uid'] = $value['uid'];
                $users[$key]['realname'] = $value['realname'];
            }
        }

        return $users;
    }

    /**
     * 根据关键词搜索记者
     * @return [type] [description]
     */
    public function getReporterListByKeyWords() {
        $q = I('get.q');
        $group_id = I('get.group_id');

        $list = array();
        if($q) {
            $map['realname'] = array('like', '%' . $q . '%');
            $map['mobile'] = $q;
            $map['realnamepy'] = array('like', '%' . $q . '%');
            $map['_logic'] = 'OR';

            $list = M('User')->alias('u')->join('__USER_INFO__ AS ui ON u.uid = ui.uid')
                ->where($map)->select();

        }

        $this->ajaxReturn($list);
    }

    /**
     * 添加用户权限
     * @return [type] [description]
     */
    public function ajaxAddReporter() {
        $uids = (array) I('post.uid');
        $group_id = I('get.group_id');
        $is_admin = session('is_admin');
        if($is_admin) {
            if($uids) {
                if($group_id) {
                    $model = M('LiveAuth');
                    foreach($uids as $val) {
                        $map['group_id'] = $group_id;
                        $map['user_id'] = $val;
                        $info = $model->where($map)->find();

                        $userArr = array();
                        if(!$info) {
                            $res = $model->add(array(
                                'group_id' => $group_id,
                                'user_id' => $val,
                                'is_scan' => 1,
                                'is_manage' => 1,
                            ));
                            $message['status'] = 1;
                            $message['msg'] = '添加成功';
                            $this->ajaxReturn($message);

                        } else {
                            $message['status'] = -1;
                            $message['msg'] = '已添加';
                            $this->ajaxReturn($message);
                        }
                    }


                } else {
                    $message['status'] = 0;
                    $message['msg'] = '无效参数';
                    $this->ajaxReturn($message);
                }

            } else {
                $message['status'] = 0;
                $message['msg'] = '无效参数';
                $this->ajaxReturn($message);
            }
        } else {
            $message['status'] = 0;
            $message['msg'] = '无权操作';
            $this->ajaxReturn($message);
        }
    }

    /**
     * 删除权限中的记者
     * @return [type] [description]
     */
    public function ajaxDelReporter() {
        $uid = I('post.uid');
        $group_id = I('get.group_id');
        $is_admin = session('is_admin');
        if($is_admin) {
            if($uid) {
                if($group_id) {
                    $res = M('LiveAuth')->where(array('group_id' => $group_id, 'user_id' => $uid))->delete();
                    if($res) {
                        $message['status'] = 1;
                        $message['msg'] = '删除成功';
                    } else {
                        $message['status'] = 0;
                        $message['msg'] = '删除失败';
                    }

                    $this->ajaxReturn($message);
                } else {
                    $message['status'] = 0;
                    $message['msg'] = '无效参数';
                    $this->ajaxReturn($message);
                }

            } else {
                $message['status'] = 0;
                $message['msg'] = '无效参数';
                $this->ajaxReturn($message);
            }
        } else {
            $message['status'] = 0;
            $message['msg'] = '无权操作';
            $this->ajaxReturn($message);
        }
    }


    public function setLivePush() {
        $group_id = I('get.group_id');
        $status = I('post.status');

        $info = M('Live')->where(array('group_id' => $group_id))->find();
        if(!$info['image_url']) {
            $message['status'] = 2;
            $message['msg'] = '未上传图片';
            $this->ajaxReturn($message);
        }

        if($group_id) {
            $res = M('Live')->where(array('group_id' => $group_id))->save(array(
                'is_push' => $status
            ));

            if($res !== false) {
                $status = M('Live')->where(array('group_id' => $group_id))->find();
                $message['status'] = $status['is_push'];
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);
            } else {
                $message['status'] = 2;
                $message['msg'] = '操作失败，请重试';
                $this->ajaxReturn($message);
            }

        } else {
            $message['status'] = 2;
            $message['msg'] = '未知ID';
            $this->ajaxReturn($message);
        }
    }

    public function setLiveTop() {
        $group_id = I('get.group_id');
        $status = I('post.status');

        if($group_id) {
            $res = M('Live')->where(array('group_id' => $group_id))->save(array(
                'is_top' => $status
            ));

            if($res !== false) {
                $status = M('Live')->where(array('group_id' => $group_id))->find();
                $message['status'] = $status['is_top'];
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);
            } else {
                $this->ajaxReturn(0);
            }

        } else {
            $this->ajaxReturn(0);
        }
    }

    public function getRecordDetail() {
        $group_id = I('get.group_id');
        if($group_id) {
            $model = M('Pv');
            // $subQuery = 'SELECT COUNT(t.id) total FROM (SELECT id FROM `whtvjw_pv` WHERE `group_id` = "' . $group_id . '" GROUP BY ip) t';
            // $seeTotal = M()->query($subQuery);
            // $count = $seeTotal[0]['total'];
            // $Page       = new \Think\Page($count,25);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            // $show       = $Page->show();// 分页显示输出
            $list = $model->where(array('group_id' => $group_id))->group('ip')->select();

            $this->ajaxReturn($list);

        } else {
            $this->ajaxReturn(0);
        }
    }


    public function getLiveThumb() {
        $live_id = I('get.liveid', 0);
        if($live_id) {
            $thumb = M('Live')->where(array('id' => $live_id))->getField('thumb');

            $this->ajaxReturn($thumb);
        } else {
            $this->ajaxReturn(0);
        }
    }

    public function ajaxSetTheme(){
        $liveid=I('get.liveid');
        $themeid=I('get.themeid');
        if($liveid!='' && $liveid!=''){
            $liveid=$liveid==0?null:$liveid;
            $res = M('Live')->where(array('group_id' => $liveid))->save(array(
                'theme_id' => $themeid
            ));

            if($res !== false) {
                $status = M('Live')->where(array('group_id' => $liveid))->find();
                $message['status'] = $status['theme_id'];
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);
            } else {
                $this->ajaxReturn(0);
            }
        }else{
            $this->ajaxReturn(0);
        }
    }

    public function addClicks($live_id,$num){
        sock_get('http://localhost/Live/Live/clicksNum.html',array('live_id'=>$live_id,'num'=>$num));
    }

    public function clicksNum($live_id,$num){
        ini_set("max_execution_time", 0);
        $rand=M('Live')->getFieldById('rand',$live_id);
        while($rand<$num){
            $n=rand(2,8);
            M('Live')->where(array('id'=>$live_id))->setInc('rand',$n);
            $rand+=$n;
            sleep(rand(2,5));
        }
    }

    /**
     * 查询直播流的帧率和码率
     * @return [type] [description]
     */
    public function getLiveStreamsFrameRateAndBitRate($id='',$sTime=0,$eTime='') {
        $flag = I('get.flag', 1);
        if($id){
            //date_default_timezone_set("Etc/GMT");
            if(!$eTime){
                $eTime=date(DATE_ISO8601,time()-8*3600).'Z';
            }else{
                $eTime=date(DATE_ISO8601,strtotime($eTime.' 23:59:59')-8*3600).'Z';
            }

            $eTime=str_replace("+0800","",$eTime);
            if(!$sTime){
                $sTime=date(DATE_ISO8601, time() - 7 * 24 * 60 * 60-8*3600).'Z';
            }else{
                $sTime=date(DATE_ISO8601,strtotime($sTime.' 00:00:00')-8*3600).'Z';
            }
            $sTime=str_replace("+0800","",$sTime);

            $live=M('Live')->field('id,group_id,realnamepy,userchannel,apply_time,user_id,return_live')
                ->alias('l')
                ->join('__USER_INFO__ ui on l.user_id=ui.uid')
                ->find($id);
            if($live['userchannel']==55 || $live['is_device']==1){
                $stream=$live['realnamepy'];
            }else{
                $stream=$live['group_id'].'_'.$live['user_id'];
            }

            $info['Action'] = 'DescribeLiveStreamsFrameRateAndBitRateData';
            $info['DomainName'] = 'jwlive.appwuhan.com';
            $info['AppName'] = 'jw';
            $info['StreamName'] = $stream;
            $info['StartTime'] = $sTime;
            $info['EndTime'] = $eTime;

            $requestid = callAliyunApi($info);
            $requestid = json_decode($requestid, true);

            $str = '';
            $arr=array();
            if(count($requestid['FrameRateAndBitRateInfos']['FrameRateAndBitRateInfo'])==0){
                if($flag) {
                    $this->ajaxReturn(array('code'=>0,'msg'=>'没有数据'));
                } else{
                    echo ('<div class="alert alert-info" role="alert">没有数据</div>');
                }

            }else{
                foreach($requestid['FrameRateAndBitRateInfos']['FrameRateAndBitRateInfo'] as $k=>$v){
                    $str.='<li><div class="intervalTime">'.($k+1) .'、'.date("Y-m-d H:i",strtotime(str_replace("Z",'-08:00',$v['Time']))) . '</div>';

                    $str .= '<div class="details">
                        <p>直播流：' . $v['StreamUrl'] . '</p>
                        <p>视频帧率：' . $v['VideoFrameRate'] . '</p>
                        <p>音频帧率：' . $v['AudioFrameRate'] . '</p>
                        <p>码率：' . $v['BitRate'] . '</p>
                    </div>';
                    $str.='</li>';

                    $arr['BitRate'][]=array(
                        (strtotime($v['Time'])+8*3600)*1000,
                        $v['BitRate']
                    );
                    $arr['VideoFrameRate'][]=array(
                        (strtotime($v['Time'])+8*3600)*1000,
                        $v['VideoFrameRate']
                    );
                    $arr['AudioFrameRate'][]=array(
                        (strtotime($v['Time'])+8*3600)*1000,
                        $v['AudioFrameRate']
                    );
                }

                $arr['BitRate']=array_reverse($arr['BitRate']);
                $arr['VideoFrameRate']=array_reverse($arr['VideoFrameRate']);
                $arr['AudioFrameRate']=array_reverse($arr['AudioFrameRate']);
                if($flag) {

                    $this->ajaxReturn($arr);
                } else{
                    echo $str;
                }

            }
        }else{
            if($flag) {
                $this->ajaxReturn(0);
            } else{
                echo ('<div class="alert alert-danger" role="alert">参数错误！</div>');
            }
        }
    }

    public function ajaxEditReturnLive(){
        if(IS_POST){
            $id=I('post.id');
            $return_live=I('post.returnLive');
            if($id){
                $res=M('Live')->save(array('id'=>$id,'return_live'=>$return_live));
                if($res !== false) {
                    echo 1;
                } else {
                    echo -1;
                }
            }else{
                $this->ajaxReturn(-1);
            }
        }else{
            $this->ajaxReturn(-1);
        }
    }

    public function ajaxGetLongRtmp($id){
        if($id){
            $res=M('Live')->alias('l')->join('__USER_INFO__ ui on l.user_id=ui.uid')->find($id);
            if($res){
                if($res['userchannel']==55 || $res['is_device']==1){
                    $stream="rtmp://jwlive.appwuhan.com/jw/" . $res['realnamepy'];
                } elseif($res['userchannel']==57) {
                    $stream="rtmp://jwlive.appwuhan.com/jwdev/" . $res['group_id'].'_'.$res['user_id'];
                }else{
                    $stream="rtmp://jwlive.appwuhan.com/jw/" . $res['group_id'].'_'.$res['user_id'];
                }
                echo authAliyun($stream,time()+3600*24);
            }else{
                ehco -1;
            }
        }
    }

    public function ajaxGetLongPushRtmp($id){
        if($id){
            $res=M('Live')->alias('l')->join('__USER_INFO__ ui on l.user_id=ui.uid')->find($id);
            if($res){
                if($res['userchannel']==55 || $res['is_device']==1){
                    $stream = authAliyun('rtmp://video-center.alivecdn.com/jw/' . $res['realnamepy'] . '?vhost=jwlive.appwuhan.com',time()+3600*24);
                } elseif($res['userchannel']==57) {
                    $stream = authAliyun('rtmp://video-center.alivecdn.com/jwdev/' . $res['group_id'] . '_' . $res['user_id'] . '?vhost=jwlive.appwuhan.com',time()+3600*24);
                }else{
                    $stream = authAliyun('rtmp://video-center.alivecdn.com/jw/' . $res['group_id'] . '_' . $res['user_id'] . '?vhost=jwlive.appwuhan.com',time()+3600*24);
                }

                echo $stream;
            }else{
                ehco -1;
            }
        }
    }
    
    public function ajaxSetLiveStatus(){
        $group_id=I('get.group_id');
        $status=I('get.status');

        switch($status){
            case 0:
                $this->ajaxGroupStreamOff($group_id);
                break;
            case 1:
                $this->ajaxGroupStreamOn($group_id);
                break;
            case 4:
                $this->ajaxGroupTesting($group_id);
                break;
            case 3:
                $this->ajaxLiveStatusOff($group_id);
                break;
        }
    }


    public function ajaxSetSort(){
        $thisGroupId=I('get.thisId');
        $thatGroupId=I('get.thatId');

        if($thisGroupId && $thatGroupId){
            $thisRes=M('Live')->where(array('group_id'=>$thisGroupId))->find();
            $thatRes=M('Live')->where(array('group_id'=>$thatGroupId))->find();

            M()->startTrans();

            if($thisRes['pos_sort']==$thatRes['pos_sort']){
                $res1=M('Live')->where(array('group_id'=>$thisGroupId))->save(array('sort_by_id'=>$thatRes['sort_by_id']));
                $res2=M('Live')->where(array('group_id'=>$thatGroupId))->save(array('sort_by_id'=>$thisRes['sort_by_id']));
            }else{
                $res1=M('Live')->where(array('group_id'=>$thisGroupId))->save(array('sort'=>$thatRes['sort']));
                echo M()->_sql();
                $res2=M('Live')->where(array('group_id'=>$thatGroupId))->save(array('sort'=>$thisRes['sort']));
                echo M()->_sql();
            }

            if($res1===false || $res2===false){
                echo false;
                M()->rollback();

            }else{
                echo true;
                M()->commit();
            }
        }else{
            echo false;
        }

    }

    public function getStreamList() {
        $group_id = I('get.group_id');
        if($group_id) {
            $list = M('Live')->where(array('group_id' => $group_id))
                    ->order('pos_sort asc, id desc')->select();
            if($list) {
                $mess['status'] = 1;
                $mess['data'] = $data;
            } else {
                $mess['status'] = -1;
                $mess['msg'] = '不存在此直播';
            }

        } else {
            $mess['status'] = -1;
            $mess['msg'] = '不存在此直播';
        }
        exit(json_encode($mess));
    }

    function verify(){
        $state = I('get.state');
        if(IS_GET) {
            $id = I('get.id');
        } elseif(IS_POST) {
            $id = I('post.id');
        }

        if(empty($id)) {
            $message['status'] = -1;
            $message['msg'] = '选项不能为空';
            $this->ajaxReturn($message);
        } else {
            $id = explode(',', $id);
        }

        // 如果要打回，但是此直播已签发了就不能执行打回操作
        // 现在只对单个的打回，没有批量
        if($state == 3) {
            $is_on = M('Publish')->where(array('live_group_id' => $id[0]))->find();
            if($is_on) {
                $this->error('此直播已签发，不能打回');
            }
        }

        $map['group_id'] = array('in', $id);
        $res = M('Live')->where($map)->save(array(
            'v_status' => $state,
        ));

        if($res !== false) {
            $this->success('审核成功');
        } else {
            $this->error('审核失败');
        }
    }

    public function setLiveVerify() {
        $group_id = I('get.group_id');
        $status = I('post.status');

        $info = M('Live')->where(array('group_id' => $group_id))->find();
        if(!$info) {
            $message['status'] = -1;
            $message['msg'] = '直播信息有误';
            $this->ajaxReturn($message);
        }

        if($group_id) {
            $res = M('Live')->where(array('group_id' => $group_id))->save(array(
                'is_verify' => $status
            ));

            if($res !== false) {
                $status = M('Live')->where(array('group_id' => $group_id))->find();
                $message['status'] = $status['is_verify'];
                $message['msg'] = '操作成功';
                $this->ajaxReturn($message);
            } else {
                $message['status'] = -1;
                $message['msg'] = '操作失败，请重试';
                $this->ajaxReturn($message);
            }

        } else {
            $message['status'] = -1;
            $message['msg'] = '未知ID';
            $this->ajaxReturn($message);
        }
    }
}